package com.huidz.calendar;

import android.Manifest;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.transition.Fade;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.google.gson.Gson;
import com.huidz.calendar.mainfragment.AlmanacFragment;
import com.huidz.calendar.mainfragment.CalendarFragment;
import com.huidz.calendar.mainfragment.CenterFragment;
import com.huidz.calendar.mainfragment.RemindFragment;
import com.huidz.calendar.model.LochtingModel;
import com.huidz.calendar.util.Apiutils;
import com.huidz.calendar.util.Url;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private ViewPager home_pager;
    private List<Fragment> fraglist;

    //ViewPager适配器
    private ViewPagerAdapter pagerAdapter;
    //底部导航栏的四个rela
    private RelativeLayout homerela, invitationrela, moneyrela, centerrela;
    private ImageView homeicon, invitationicon, moneyicon, centericon;
    private TextView hometext, invitationtext, moneytext, centertext;

    /*****************************/


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Fade fade = new Fade();
        fade.setDuration(200L);//间歇时间
        getWindow().setEnterTransition(fade);
        if(Build.VERSION.SDK_INT>=23){
            String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.CALL_PHONE,Manifest.permission.READ_LOGS,Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.SET_DEBUG_APP,Manifest.permission.SYSTEM_ALERT_WINDOW,Manifest.permission.GET_ACCOUNTS,Manifest.permission.WRITE_APN_SETTINGS};
            ActivityCompat.requestPermissions(this,mPermissionList,123);
        }
        setContentView(R.layout.activity_main);
        inti();

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if(!Url.USER_ID.equals("")){
            // 调用 Handler 来异步设置别名
            mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, "calendar_"+Url.USER_ID));
        }
    }

    public TagAliasCallback getmAliasCallback =new TagAliasCallback() {
        @Override
        public void gotResult(int i, String s, Set<String> set) {
            String logs ;
            switch (i) {
                case 0:
                    logs = "Set tag and alias success";
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    // 延迟 60 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, "calendar_123456"), 1000 * 60);
                    break;
                default:
                    logs = "Failed with errorCode = " + i;
            }
        }
    };
    private static final int MSG_SET_ALIAS = 1001;
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    // 调用 JPush 接口来设置别名。
                    JPushInterface.setAliasAndTags(getApplicationContext(),
                            (String) msg.obj,
                            null,
                            getmAliasCallback);
                    break;
                default:
                    break;
            }
        }
    };


    private SharedPreferences mSharedPreferences;
    private SharedPreferences.Editor mEditor;
    /**
     * 初始化加载调用方法
     */
    public void inti() {
        home_pager = findViewById(R.id.home_pager);
        AddFragment();
        BottomRela();
        ChangeColor(0);
        Apiutils.isNetworkConnecteds = Apiutils.isNetworkConnected(MainActivity.this);
        get(Url.latitude, Url.longitude);
        mSharedPreferences = getSharedPreferences("login", MODE_PRIVATE);  //名称和类型
        mEditor = mSharedPreferences.edit();
        mEditor.putString("islogin", "1");
        mEditor.apply();
        mEditor.commit();
    }

    /**
     * 改变颜色状态
     *
     * @param i 为viewpager的下标，通过下标改变导航栏字体图标
     */
    public void ChangeColor(int i) {
        if (i == 0) {
            homeicon.setBackgroundDrawable(getResources().getDrawable(R.mipmap.rlc));
            invitationicon.setBackgroundDrawable(getResources().getDrawable(R.mipmap.hl));
            moneyicon.setBackgroundDrawable(getResources().getDrawable(R.mipmap.tx));
            centericon.setBackgroundDrawable(getResources().getDrawable(R.mipmap.wd));
            hometext.setTextColor(getResources().getColor(R.color.title_color));
            invitationtext.setTextColor(getResources().getColor(R.color.text_black));
            moneytext.setTextColor(getResources().getColor(R.color.text_black));
            centertext.setTextColor(getResources().getColor(R.color.text_black));
        }
        else if (i == 1) {
            homeicon.setBackgroundDrawable(getResources().getDrawable(R.mipmap.rl));
            invitationicon.setBackgroundDrawable(getResources().getDrawable(R.mipmap.hlc));
            moneyicon.setBackgroundDrawable(getResources().getDrawable(R.mipmap.tx));
            centericon.setBackgroundDrawable(getResources().getDrawable(R.mipmap.wd));
            hometext.setTextColor(getResources().getColor(R.color.text_black));
            invitationtext.setTextColor(getResources().getColor(R.color.title_color));
            moneytext.setTextColor(getResources().getColor(R.color.text_black));
            centertext.setTextColor(getResources().getColor(R.color.text_black));
        }
        else if (i == 2) {
            homeicon.setBackgroundDrawable(getResources().getDrawable(R.mipmap.rl));
            invitationicon.setBackgroundDrawable(getResources().getDrawable(R.mipmap.hl));
            moneyicon.setBackgroundDrawable(getResources().getDrawable(R.mipmap.txc));
            centericon.setBackgroundDrawable(getResources().getDrawable(R.mipmap.wd));
            hometext.setTextColor(getResources().getColor(R.color.text_black));
            invitationtext.setTextColor(getResources().getColor(R.color.text_black));
            moneytext.setTextColor(getResources().getColor(R.color.title_color));
            centertext.setTextColor(getResources().getColor(R.color.text_black));
        } else {
            homeicon.setBackgroundDrawable(getResources().getDrawable(R.mipmap.rl));
            invitationicon.setBackgroundDrawable(getResources().getDrawable(R.mipmap.hl));
            moneyicon.setBackgroundDrawable(getResources().getDrawable(R.mipmap.tx));
            centericon.setBackgroundDrawable(getResources().getDrawable(R.mipmap.wdc));
            hometext.setTextColor(getResources().getColor(R.color.text_black));
            invitationtext.setTextColor(getResources().getColor(R.color.text_black));
            moneytext.setTextColor(getResources().getColor(R.color.text_black));
            centertext.setTextColor(getResources().getColor(R.color.title_color));
        }
    }

    public class MyPagerChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            ChangeColor(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    }

    /**
     * 用于绑定fragment
     */
    public void AddFragment() {
        //添加frag到集合中
        fraglist = new ArrayList<>();
        fraglist.add(new CalendarFragment());
        fraglist.add(new AlmanacFragment());
        fraglist.add(new RemindFragment());
        fraglist.add(new CenterFragment());
        //绑定点击事件
        home_pager.setOnPageChangeListener(new MyPagerChangeListener());
        //绑定适配器
        pagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), fraglist);
        home_pager.setAdapter(pagerAdapter);
        home_pager.setCurrentItem(0);
        home_pager.setOffscreenPageLimit(4);
    }


    /**
     * 底部四个按键
     */
    public void BottomRela() {
        homerela = findViewById(R.id.homerela);
        invitationrela = findViewById(R.id.invitationrela);
        moneyrela = findViewById(R.id.moneyrela);
        centerrela = findViewById(R.id.centerrela);
        homerela.setOnClickListener(this);
        invitationrela.setOnClickListener(this);
        moneyrela.setOnClickListener(this);
        centerrela.setOnClickListener(this);
        homeicon = findViewById(R.id.homeicon);
        invitationicon = findViewById(R.id.invitationicon);
        moneyicon = findViewById(R.id.moneyicon);
        centericon = findViewById(R.id.centericon);
        hometext = findViewById(R.id.hometext);
        invitationtext = findViewById(R.id.invitationtext);
        moneytext = findViewById(R.id.moneytext);
        centertext = findViewById(R.id.centertext);

    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.homerela:
                home_pager.setCurrentItem(0);
                ChangeColor(0);
                break;

            case R.id.invitationrela:
                home_pager.setCurrentItem(1);
                ChangeColor(1);
                break;

            case R.id.moneyrela:
                home_pager.setCurrentItem(2);
                ChangeColor(2);
                break;

            case R.id.centerrela:
                home_pager.setCurrentItem(3);
                ChangeColor(3);
                break;
        }
    }

    public static long firstTime = 0;

    /***
     * 退出应用
     * @param keyCode
     * @param event
     * @return
     */
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                long secondTime = System.currentTimeMillis();
                if (secondTime - firstTime > 2000) { // 如果两次按键时间间隔大于2秒，则不退出
                    Apiutils.SetToast(MainActivity.this, "再按一次退出程序");
                    firstTime = secondTime; // 更新firstTime
                    return true;
                } else { // 两次按键小于2秒时，退出应用
//                    System.exit(0);
                    finishAffinity();
                }
                break;
        }
        return super.onKeyUp(keyCode, event);
    }


    public void get(String lat, String lng) {
        OkHttpClient client = new OkHttpClient();
        //构造Request对象
        //采用建造者模式，链式调用指明进行Get请求,传入Get的请求地址
        Request request = new Request.Builder().get().url(Url.GETADDRESS + "?lat=" + lat + "&lng=" + lng).build();
        Call call = client.newCall(request);
        //异步调用并设置回调函数
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, final Response response) {
                try {
                    final String responseStr;
                    responseStr = response.body().string();
                    Message message = new Message();
                    message.obj = responseStr;
                    gethot.sendMessage(message);
                } catch (Exception e) {
                    Apiutils.SetLog(e.toString() + "");
                    e.printStackTrace();
                }
            }
        });
    }

    public static LochtingModel userm;
    public Handler gethot = new Handler() {
        public void handleMessage(Message msg) {
            String msgs = null;
            try {
                JSONObject success_Object = null;
                if (msg.obj != null) {
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    msgs = success_Object.getString("msg");
                    if (code.equals("1")) {
                        Gson gson = new Gson();
                        userm = gson.fromJson(msg.obj.toString(),
                                LochtingModel.class);
                        Url.address_code = userm.getData().getCode();
                    } else
                        Apiutils.SetToast(MainActivity.this, msgs + "");
                }

            } catch (
                    Exception e) {
                e.printStackTrace();
            }
        }
    };

}
